// import { menu } from '@/services/ant-design-pro/menus';
import { getMenuList as queryMenu } from '@/services/menu';
import { getCategoryList } from '@/services/category';
import {
  getMenuIdListByRoleId,
  updateRoleMenuList,
  getCataIdListByRoleId,
  updateRoleCataList
} from '@/services/permission';
import rubberstamp from '@/assets/images/rubberstamp.png';

import { batchDelete, createRole, getRoleList, updateRole } from '@/services/roleService';
import {
  ApartmentOutlined,
  AuditOutlined,
  DeleteOutlined,
  EditOutlined,
  FileDoneOutlined,
  ForkOutlined,
  PlusOutlined
} from '@ant-design/icons';
import {ModalForm, ProFormSelect, ProFormText} from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {Button, Checkbox, Divider, message, TreeSelect} from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import AuthorityForm from './components/authorityForm';
import type { FormValueType } from './components/UpdateForm';
import UpdateForm from './components/UpdateForm';
import {getSubSystemList} from "@/services/subSystem";
const TableList: React.FC = () => {
  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.RoleListItem) => {
    try {
      await createRole({ ...fields });
      message.success('添加成功！');
      return true;
    } catch (error) {
      message.error('添加失败!');
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: FormValueType) => {
    try {
      await updateRole({
        ...fields,
        id: currentRow.id,
      });

      message.success('更新成功！');
      return true;
    } catch (error) {
      message.error('更新失败！');
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除多个节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.RoleListItem[]) => {
    if (!selectedRows) return true;
    try {
      await batchDelete(selectedRows.map((row) => row.id));
      message.success('已删除！');

      if (actionRef.current) {
        actionRef.current.reload();
        actionRef.current.clearSelected();
      }
      return true;
    } catch (error) {
      message.error('删除失败！');
      return false;
    }
  };

  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  /**
   * 权限分配窗口
   */
  const [authorityModalVisible, handleAuthorityModalVisible] = useState<boolean>(false);
  const [cataModalVisible, handleCataModalVisible] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const [flg, setFlg] = useState<boolean>('');

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RoleListItem>();
  const [selectedRows, setSelectedRows] = useState<API.RoleListItem[]>([]);
  const [menuList, setMenuList] = useState<API.MenuListItem[]>([]);
  //全选
  const [checkAll, setCheckAll] = useState<boolean>(false);
  //
  const [menuArr, setMenuArr] = useState<any[]>([]);
  const [menuAllArr, setMenuAllArr] = useState<[]>([]);

  const [cataArr, setCataArr] = useState<any[]>([]);

  const [cataAllArr, setCataAllArr] = useState<[]>([]);
  const { SHOW_PARENT } = TreeSelect;
  //selectArr
  const [selectArr, setSelectArr] = useState<[]>([]);
  //获取菜单
  const categoryChange = (newValue: string[]) => {
    console.log('onChange ', newValue);
    setCataArr(newValue);
  };

  const fetchMenu = async () => {
    await queryMenu({}).then(function (res) {
      const resList = res?.data;
      let menuArr = [];
      let allIds = [];
      if (resList.length > 0 && resList != undefined) {
        resList.forEach((item) => {
          let childrenArr = [];
          let ids = [];
          if (item?.children && item.children.length > 0) {
            item.children.forEach((item) => {
              ids.push(item.id);
              childrenArr.push({
                value: item.id,
                label: item.name,
              });
            });
          }
          allIds.push({
            label: item.name,
            labelId: item.id,
            value: ids,
          });
          menuArr.push({
            value: ids,
            label: item.name,
            labelId: item.id,
            children: childrenArr,
          });
        });
        setMenuArr(menuArr);
        setMenuAllArr(allIds);
      }
    });

  };
  const getCata = async (record,filterType)=>{
    setFlg(filterType)
    const res  = await getCategoryList({ type: 'topic',roleId:record?.id,filterType})
    const resList = res?.data;
    if(!record){
      resList.map(i=>{
        i.title = i.name
        i.value = i.id
        i.label = i.name
        if(i.children){
          i.children.map(j=>{
            j.title = j.name
            j.value = j.id
            j.label = j.name
            return j
          })
        }
        return i
      })
      setCataAllArr(resList)
    }else{
      const ids = resList.map(i=> {
        let ids = []
        ids.push(i.id)
        if(i.children){
          ids.push(...i.children.map(i=>i.id))
        }
        return ids
      }).flat(Infinity)
      console.log(ids,'ids');
      setCataArr(ids)
    }
  }
  //初始化加载菜单
  useEffect(() => {
    fetchMenu();
    getCata(null);
  }, []);

  const isAllRight = (list) => {
    if (list.length == 0) {
      return setCheckAll(false);
    }
    for (let i = 0; i < menuArr.length; i++) {
      const element = menuArr[i];
      const obj = list.filter((item) => item.label == element.label);
      if (obj.length > 0) {
        if (obj[0].value.length != element.value.length) {
          return setCheckAll(false);
        }
      }
    }
    setCheckAll(true);
  };
  const getRolesById = async (id) => {
    const res = await getMenuIdListByRoleId({ roleId: id });
    if (res.code == '0') {
      setSelectArr(res?.data.menuIdList);
      isAllRight(res?.data.menuIdList);
      handleAuthorityModalVisible(true);
    }
  };
  const getCataById = async (id) => {
    const res = await getCataIdListByRoleId({ cata: id });
    if (res.code == '0') {
      setSelectArr(res?.data.menuIdList);
      isAllRight(res?.data.menuIdList);
      handleAuthorityModalVisible(true);
    }
  };

  const columns: ProColumns<any>[] = [
    {
      title: '角色名称',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'roleName',

    },

    {
      title: '备注',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'roleDes',
      render: (_, record) => [
        <span>{record.roleDes || '普通用户'}</span>
      ]
    },
    {
      title: '创建时间',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdTime',
      valueType: 'dateTime',
    },
    {
      title: '更新时间',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'updatedTime',
      valueType: 'dateTime',
    },
    {
      title: '最后操作人',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'createdBy',
    },
    {
      title: '操作',
      align: 'left',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="edit"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          <Button className={'buttonMargin'} shape={'round'} type="primary" icon={<EditOutlined />}>
            编辑
          </Button>
        </a>,
        <a
          key="sendCata"
          onClick={async () => {
            await getCata(record,'sub')
            handleCataModalVisible(true);
            setCurrentRow(record);
          }}
        >

          <Button className={'buttonMargin'} shape={'round'} icon={<ApartmentOutlined />}>
            发布权限
          </Button>
        </a>,
        <a
          key="sendRole"
          onClick={() => {
            getRolesById(record.id);
            setCurrentRow(record);
          }}
        >

          <Button className={'buttonMargin'} shape={'round'} icon={<ForkOutlined />}>
            功能权限
          </Button>
        </a>,
        record.authId != 2 ?
          [
            <a
              key="approve"
              onClick={async () => {
                // getRolesById(record.id);
                // handleUpdateModalVisible(true);
                await getCata(record,'check')
                handleCataModalVisible(true);
                setCurrentRow(record);
              }}
            >
              <Button className={'buttonMargin'} shape={'round'} icon={<AuditOutlined />}>
                审核权限
              </Button>
            </a>]
          : null,

        <a
          key="delete"
          style={{ color: 'red' }}
          onClick={() => {
            handleRemove([record]);
          }}
        >
          <Button danger className={'buttonMargin'} shape={'round'} icon={<DeleteOutlined />}>
            删除
          </Button>
        </a>,
      ],
    },
  ];

  //checkBox
  //全选
  const onChange = (e) => {
    setCheckAll(e.target.checked);
    if (e.target.checked) {
      //调用接口
      setSelectArr(menuAllArr);
    } else {
      //取消全选
      setSelectArr([]);
    }
  };
  const formLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } };
  return (
    <PageContainer>
      <ProTable<API.RoleListItem, API.PageParams>
        headerTitle="角色列表"
        actionRef={actionRef}
        rowKey="id"
        search={false}
        tableStyle={{ textAlign: 'center' }}
        options={false}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined />
            添加
          </Button>,
          <Button
            type="primary"
            danger
            key="danger"
            onClick={() => {
              handleRemove(selectedRows);
            }}
          >
            <DeleteOutlined />
            批量删除
          </Button>,
        ]}
        request={getRoleList}
        columns={columns}
        rowSelection={{
          alwaysShowAlert: false,
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      <ModalForm
        title="新建角色"
        width="600px"
        layout={'horizontal'}
        {...formLayout}
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        modalProps={{ destroyOnClose: true }}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.RoleListItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '角色名称必填！',
            },
          ]}
          width="md"
          name="roleName"
          placeholder="请输入角色名称"
          label="角色名称"
        />
        <ProFormSelect
          initialValue={currentRow?.roleId}
          width="md"
          label="角色类型"
          // width="60%"
          name="roleId"
          placeholder="请选择"
          request={async () => {
            // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
            // 如果需要转化参数可以在这里进行修改
            const msg = await getRoleList({page:1,pageSize:100});
            const res = msg.data.map(i=>{
              i.value = i.id
              i.label = i.roleName
              return i
            }).filter(i=>{
              if([2,3,4,5].includes(i.id)){
                return i
              }
            })
            return res;
          }}
        />
        <ProFormText width="md" name="roleDes" placeholder="请输入备注" label="备注" />
      </ModalForm>
      <ModalForm
        title="分配权限"
        width="600px"
        layout={'horizontal'}
        {...formLayout}
        visible={authorityModalVisible}
        onVisibleChange={handleAuthorityModalVisible}
        modalProps={{ destroyOnClose: true }}
        onFinish={async (value) => {
          const params = {
            menuIdList: selectArr,
            roleId: currentRow.id,
            roleName: currentRow.roleName,
          };
          const success = await updateRoleMenuList(params);
          if (success.code == '0') {
            handleAuthorityModalVisible(false);
            message.success('分配权限成功');
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >

        <Checkbox onChange={onChange} checked={checkAll}>
          全部
        </Checkbox>
        <Divider />
        {menuArr?.map((item, index) => {
          let selectValue = [];
          if (selectArr.length > 0) {
            const selectedOne = selectArr.filter((obj) => obj.label == item.label);
            if (selectedOne.length > 0) {
              selectValue = selectedOne[0].value;
            }
          }

          return (
            <AuthorityForm
              key={index}
              menuObj={item}
              label={item.label}
              labelId={item.labelId}
              selectValue={selectValue}
              selectArr={selectArr}
              setSelectArr={setSelectArr}
              checkAll={checkAll}
            />
          );
        })}
      </ModalForm>
      <ModalForm
        title="分配栏目"
        width="600px"
        layout={'horizontal'}
        modalProps={{ destroyOnClose: true }}
        {...formLayout}
        visible={cataModalVisible}
        onVisibleChange={ bool=>{
          handleCataModalVisible(bool)
          if(!bool) {
            setCataArr([])
          }
        } }
        modalProps={{ destroyOnClose: true }}
        onFinish={async (value) => {
          let params = {
            catas:'',
            roleId: currentRow.id,
            roleName: currentRow.roleName,
            checkCataList:'',
          };
          if(flg == 'sub') {
            params.catas = cataArr.join(',')
            params.checkCataList = null
          }else{
            params.catas = null
            params.checkCataList = cataArr.join(',')
          }

          const success = await updateRoleCataList(params);
          if (success.code == '0') {
            message.success('分配权限成功');
            if (actionRef.current) {
              actionRef.current.reload();
            }
            return true
          }
        }}

      >
        <TreeSelect allowClear onSelect={val=>{
          cataAllArr.map(i=>{
            if(i.id != val) return
            console.log(val,i,'onSelect');
            let ids = [...cataArr,i.id]
            if(i.children){
              // const item = i.children.map(j => j.id == val)
              // if(item.length > 0){
              ids.push(...i.children.map(i=>i.id))
              ids = Array.from(new Set(ids))
              // }
            }
            console.log(ids,'ids');
            setCataArr(ids)

          })
        }} onChange={categoryChange}
                            showCheckedStrategy={SHOW_PARENT} style={{width:'100%'}} multiple treeCheckable
                    value={cataArr} treeData={cataAllArr}
        />
        <Divider />

      </ModalForm>

      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
        key={new Date().getTime()}
      />
    </PageContainer>
  );
};

export default TableList;
